#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理控制器（合并版本）
将路由和控制器合并到一个类中
"""

from flask import Blueprint, jsonify, request, current_app
from services.app_service import AppService
from settings import get_logger

# API版本
API_VERSION = 'v1'

# 创建蓝图
config_bp = Blueprint('config', __name__, url_prefix='/api')

class ConfigController:
    """
    配置管理控制器
    负责配置获取和更新的路由处理
    """
    
    def __init__(self):
        """
        初始化控制器并注册路由
        """
        self.app_service = AppService()
        self.logger = get_logger(__name__)
        self._register_routes()
    
    def _register_routes(self):
        """
        注册路由
        """
        config_bp.route('/config', methods=['GET'])(self.get_config)
        config_bp.route('/config', methods=['POST'])(self.update_config)
    
    def get_config(self):
        """
        获取当前配置
        
        Returns:
            JSON: 配置信息
        """
        self.logger.info("获取当前配置")
        try:
            app_instance = self.app_service.get_app_instance()
            
            if not app_instance:
                return jsonify({
                    "success": False,
                    "error": "微信后端应用未初始化"
                }), 500
            
            config = app_instance.get_config()
            return jsonify({
                "success": True,
                "data": config
            })
            
        except Exception as e:
            current_app.logger.error(f"获取配置失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500
    
    def update_config(self):
        """
        更新配置
        
        Returns:
            JSON: 更新结果
        """
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    "success": False,
                    "error": "请求数据为空"
                }), 400
            
            self.logger.info(f"更新配置，类型：{data.get('type', '未指定')}")
            
            app_instance = self.app_service.get_app_instance()
            
            if not app_instance:
                return jsonify({
                    "success": False,
                    "error": "微信后端应用未初始化"
                }), 500
            
            config_type = data.get('type')
            if not config_type:
                return jsonify({
                    "success": False,
                    "error": "缺少配置类型"
                }), 400
            
            # 提取配置参数
            config_params = {k: v for k, v in data.items() if k != 'type'}
            
            success = app_instance.update_config(config_type, **config_params)
            
            if success:
                return jsonify({
                    "success": True,
                    "message": "配置更新成功"
                })
            else:
                return jsonify({
                    "success": False,
                    "error": "配置更新失败"
                }), 500
                
        except Exception as e:
            current_app.logger.error(f"更新配置失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500

# 实例化控制器，确保路由被注册
config_controller = ConfigController()